package com.controller;

import com.controller.vo.ResultVO;
import com.entity.Plate;
import com.service.PlateService;
import com.utils.UploadImage;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * ClassName: PlateController
 * Description:
 *
 * @author L_Z_R
 * @version 1.0
 * @create 2025/05/23 11:27
 */
@RestController
public class PlateController extends BaseController {
    @Autowired
    private PlateService plateService;

    @PostMapping(path ="addPlate", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultVO<String> addPlate(@RequestPart("plate")Plate plate,
                                     @RequestPart(value = "files",required = false) MultipartFile[] files,
                                     HttpServletRequest request
                                     ) throws IOException {

        // 查看板块名称是否已经存在
        if (plateService.isPlateExist(plate.getPlateName())) {
            return success("板块名称已存在");
        }

        // 设置板块的默认图片
        String defaultImagePath ="images/plateDefault.png";

        //4. 保存所有文件到该目录下
        List<String> addFiles = new ArrayList<>();
        if (files != null) {
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    String imagePath = request.getContextPath() + "/images/" + UploadImage.uploadImage(file, request);
                    addFiles.add(imagePath);
                }
            }
        }

        //5. 将路径添加进 Plate 媒体对象中
        if (!addFiles.isEmpty()){
            // 使用逗号分隔路径，你也可以根据需求使用其他分隔符
            String joinedPaths = String.join(",", addFiles);
            plate.setPlateImg(joinedPaths);
        } else {
            plate.setPlateImg(defaultImagePath);
        }

        plateService.addPlate(plate);
        return success("上传成功");
    }

    @GetMapping("getAllPlate")
    public ResultVO<List<Plate>> getAllPlate() {
        return success(plateService.getAllPlate());
    }

    @GetMapping("getPlateById")
    public ResultVO<Plate> getPlateById(int id) {
        return success(plateService.getPlateById(id));
    }

    @PostMapping("deletePlate")
    public ResultVO<String> deletePlate(Integer plateId) {
        plateService.deletePlate(plateId);
        return success();
    }

    @PostMapping("updatePlate")
    public ResultVO<String> updatePlate(Plate plate) {
        plateService.updatePlate(plate);
        return success();
    }

    @GetMapping("selectHotPlate")
    public ResultVO<List<Plate>> selectHotPlate() {
        return success(plateService.selectHotPlates());
    }
}
